﻿using System.Collections.Generic;
using System.IO;
using Lucid.ESA.ClientDataSystem.Data.Common;
using Lucid.ESA.ClientDataSystem.Data.Repositories;
using Lucid.ESA.ClientDataSystem.Domain.Entities;
using Lucid.ESA.ClientDataSystem.Domain.RepositoryContracts;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Lucid.ESA.ClientDataSystem.UnitTests.Data
{
    [TestClass]
    public class ClientRepositoryTest
    {
        [ClassInitialize()]
        public static void MyClassInitialize(TestContext testContext)
        {
            //Set the test context in the session provider, so that it only creates one sesion
            //per test.
            SessionProvider.CurrentTestContext = testContext;
        }

        [ClassCleanup()]
        public static void MyClassCleanup() { }

        [TestInitialize()]
        public void MyTestInitialize() 
        {
            //Get a fresh copy of the database.
            if (File.Exists("ClientDataSystem.sdf"))
                File.Delete("ClientDataSystem.sdf");

            File.Copy("InitialClientDataSystem.sdf", "ClientDataSystem.sdf");
        }
        
        [TestCleanup()]
        public void MyTestCleanup()
        { 
            //Ensure session is closed after each test.
            SessionProvider.CloseSession();
        }

        [TestMethod]
        public void CanGetAllClients()
        {
            IClientRepository clientRepository = new ClientRepository();
            IList<Client> clients = clientRepository.GetAll();
            Assert.AreEqual(3, clients.Count);            
        }

        [TestMethod]
        public void CanGetClientById()
        {
            IClientRepository clientRepository = new ClientRepository();
            Client client = clientRepository.GetById(1L);
            Assert.AreEqual(1, client.Id.Value);
            Assert.AreEqual("Indigo Industries", client.Name);
            Assert.AreEqual(2, client.Sites.Count);
            Assert.AreEqual(2, client.Contacts.Count);
        }

        [TestMethod]
        public void CanAddClient()
        {
            IClientRepository clientRepository = new ClientRepository();
            Client client = Client.Create("Gold PLC");
            using (ITransactionProvider transactionProvider = new TransactionProvider())
            {
                transactionProvider.BeginTransaction();
                clientRepository.Save(client);
                transactionProvider.CommitTransaction();
            }
            long newId = client.Id.Value;
            SessionProvider.CloseSession();
            Client client2 = clientRepository.GetById(newId);
            Assert.AreEqual("Gold PLC", client2.Name);
        }
    }
}
